﻿#include "BarcodeCreator.h"

BarcodeCreator::BarcodeCreator()
    :m_background(Qt::white),
      m_foreground(Qt::black)
{

}

QImage BarcodeCreator::toImage(QSize sz, QImage::Format format) const
{
    if( !isValid() ) return QImage();
    if(sz == QSize(0, 0))
    {
        sz = size() * 4;//QSize(width * 4, height * 4);
    }
    QImage image(sz, format);
    QPainter painter(&image);
    painter.setBrush(m_background);
    painter.setPen(Qt::NoPen);
    painter.drawRect(0, 0, sz.width(), sz.height());
    painter.setBrush(m_foreground);
    renderNoBackground(painter, sz.width(), sz.height());
    return image;
}

void BarcodeCreator::setColor(QColor foreground, QColor background)
{
    m_background = background;
    m_foreground = foreground;
}

bool BarcodeCreator::renderNoBackground(QPainter &painter, int width, int height) const
{
    QRect rect(0, 0, width, height);
    return renderNoBackground(painter, rect);
}

bool BarcodeCreator::saveImage(QString fileName, QSize size) const
{
    QImage image = toImage(size);
    return image.save(fileName);
}

bool BarcodeCreator::render(QPainter &painter, QColor background, QColor foreground, QRect rect) const
{
    if(!isValid()) return false;

    if(rect.isNull())
    {
        int width = size().width();
        int height = size().height();
        rect.setRect(0, 0, width * 4, height * 4);
    }
    painter.save();
    painter.setPen(Qt::NoPen);
    painter.setBrush(background);
    painter.drawRect(rect);
    painter.setBrush(foreground);
    bool ret = renderNoBackground(painter, rect);
    painter.restore();
    return ret;
}
